package com.leyou.item.web;

import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.service.CategoryService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("category")
public class CategoryController {

    private final CategoryService categoryService;

    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    /**
     * 根据id查询分类
     * @param id 分类id
     * @return 分类对象
     */
    @GetMapping("/{id}")
    public ResponseEntity<CategoryDTO> queryCategoryById(@PathVariable("id") Long id) {
        // 查询
        Category category = categoryService.getById(id);
        // 转换DTO
        CategoryDTO categoryDTO = new CategoryDTO(category);
        // 查询成功，一般返回200
        return ResponseEntity.ok(categoryDTO);
//        return ResponseEntity.ok(new CategoryDTO(categoryService.getById(id)));
        // select id from dual
    }

    /**
     * 根据id集合查询分类集合
     * @param ids id集合
     * @return 分类的集合
     */
    @GetMapping("/list")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByIds(@RequestParam("ids") List<Long> ids){
        // 查询
        List<Category> list = categoryService.listByIds(ids);
        // 转换DTO
        List<CategoryDTO> dtoList = CategoryDTO.convertEntityList(list);
        // 返回
        return ResponseEntity.ok(dtoList);
    }

    /**
     * 根据父类目的id查询子类目的集合
     * @param parentId 父类目id
     * @return 子类目集合
     */
    @GetMapping("/of/parent")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByParent(@RequestParam("pid") Long parentId){
        // SELECT * FROM tb_category WHERE parent_id = 0
        List<Category> list = categoryService.query().eq("parent_id", parentId).list();
        // 转换DTO
        List<CategoryDTO> dtoList = CategoryDTO.convertEntityList(list);
        // 返回
        return ResponseEntity.ok(dtoList);
    }

    /**
     * 根据品牌查询分类
     * @param brandId 品牌id
     * @return 分类的集合
     */
    @GetMapping("/of/brand")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByBrand(@RequestParam("id") Long brandId){
        // 根据品牌查询分类
        List<CategoryDTO> list = categoryService.queryCategoryByBrand(brandId);
        // 返回
        return ResponseEntity.ok(list);
    }

}
